<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
    <link href="lib/mapbox-gl2.6.1.css" rel="stylesheet">
    <script src="lib/mapbox-gl2.6.1.js"></script>
    <script src="lib/jquery-3.6.0.min.js"></script>
    <script src='lib/mapbox-gl-language.js'></script>
    <script src="lib/dat.gui.min.js"></script>
    <script src="lib/echarts.min.js"></script>
    <script src="lib/ecStat.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
        }

        #map {
            /* position: absolute; */
            width: 100%;
            height:600px;
        }
    </style>
</head>

<body>
    <div id="map"></div>
    <div id="chart1" style="height: 300px;"></div>
    <div id="chart2" style="height: 100px;"></div>

    <script type="module">
        import statchart from './statchart.js';
        import * as turf from './lib/turf.min.js';
        console.log(statchart)
        console.log(turf)
        /** 面图层geojson密度分布，全省建议到乡，分市到村 */
        mapboxgl.accessToken = 'pk.eyJ1IjoiaG91eGlleXUiLCJhIjoiY2pldjE5amU3NndzeDM5bzd5bm9ncDgycyJ9.j1F-Lgid3L5k2Abm8_xTeQ';
        const map = new mapboxgl.Map({
            container: 'map',
            style: 'mapbox://styles/mapbox/dark-v10',
            center: [117.974103, 36.374436],
            zoom: 7
        });
        map.addControl(
            new MapboxLanguage({
                defaultLanguage: "zh-Hans",
            })
        );
        map.on('load', async () => {
            // Add a geojson point source.
            // Heatmap layers also work with a vector tile source.
            let ip1 = '192.168.0.53:8080';
            let ipapi = '6ql20nip.ipyingshe.net';
            let level = 'xian'
            let field = 'f176'
            let area = '37'
            //县级4.6M，乡级20M(39s)
            let url2 = encodeURI(`http://${ipapi}/geoserver/rp7/ows?service=WFS&version=1.0.0&request=GetFeature&outputFormat=application/json&typeName=rp7:gv_${level}&propertyName=geom,area,codename,${field}&format_options=id_policy:reference_no=false&cql_filter=code like '${area}%'`)
            //可抽稀，0.001精度，县级2M，乡级7M(25s),村级14M
            // let url3 = `http://${ipapi}/features?areacode=&field=${field}&level=${level}&simplify=0.001`
            let geodata = await $.getJSON(url2);
            // console.log(geodata.features.map(f => f.properties.f176  / f.properties.area))
            //计算密度，并排序
            let ar_data = geodata.features.map(f => (f.properties.area==null?0:f.properties.f176  / f.properties.area)??0)//.sort((a,b)=>a-b);
            let ar_name = geodata.features.map(f => f.properties.codename)//.sort((a,b)=>a-b);

            //绘制直方图
            statchart.histogram('chart1',ar_data,ar_name)
            statchart.boxplot('chart2',ar_data,ar_name)
            //获取最大最小值
            let minmax = await $.getJSON(encodeURI(`http://${ipapi}/getminmax?field=${field}/area&level=${level}&filter=code like '3701%'`));
            let min = minmax.min;
            let max = minmax.max;
            var options = {
                'title': '密度分布',
                min: min,
                max: max,
                colormin: [250, 250, 250, 1],
                colormax: [120, 0, 0, 1]
            };;

            /** 参数配置组件 */
            initOptions(map, options);

            // console.log(max, geodata.features)
            // console.log(geodata)
            map.addSource('bj', {
                'type': 'geojson',
                'data': geodata,
                // promoteId:'code'
                generateId: true
            });

            // Add a layer showing the state polygons.
            map.addLayer({
                'id': 'states-layer',
                'type': 'fill',
                'source': 'bj',
                'paint': {
                    'fill-color': [
                        'interpolate',
                        ['linear'],
                        ['/',['get', 'f176'], ['get', 'area']],
                        options.min,
                        `rgba(${options.colormin.join(',')})`,
                        options.max,
                        `rgba(${options.colormax.join(',')})`,
                    ],
                    // 'fill-outline-color': 'rgba(200, 100, 240, 1)'
                }
            });

            const popup = new mapboxgl.Popup({
                closeButton: false
            });

            map.addLayer({
                'id': 'states-highlighted',
                'type': 'fill',
                'source': 'bj',
                'paint': {
                    'fill-outline-color': '#484896',
                    'fill-color': '#6e599f',
                    'fill-opacity': 0.75
                },
                'filter': ['==', ['id'], '']
            }
            );
            map.addLayer({
                id: "label_buildings",
                type: "symbol",
                source: "bj",
                layout: {
                    "text-field": "{codename}",
                    // "text-font": ["DIN Offc Pro Medium", "Arial Unicode MS Bold"],
                    "text-size": 10,
                    "text-offset": [0, -1.5],
                    // "text-allow-overlap": true
                },
                paint: {
                    "text-halo-width": 1,
                    "text-halo-color": "white",
                },
            });
            map.on('mousemove', 'states-layer', (e) => {
                // Change the cursor style as a UI indicator.
                map.getCanvas().style.cursor = e.features.length ? 'pointer' : '';

                popup.setLngLat(e.lngLat)
                    .setHTML(`<b>${e.features[0].properties.codename}</b><br>人口数：${e.features[0].properties.f176}<br>面积：${(e.features[0].properties.area).toFixed(2)}平方公里<br>人口密度：${(e.features[0].properties.f176  / e.features[0].properties.area).toFixed(2)}人/km`)
                    .addTo(map);

                map.setFilter('states-highlighted', ['==', ['id'], e.features[0].id]);
            });

            map.on('mouseleave', 'states-layer', () => {
                map.getCanvas().style.cursor = '';
                popup.remove();
                map.setFilter('states-highlighted', ['==', ['id'], '']);
            });
        });

        function initOptions(map, options) {
            // var Options = function () 
            var gui = new dat.GUI();

            gui.add(options, 'title');
            console.log(options)
            var ctlmin = gui.add(options, 'min').min(options.min).max(options.max);
            var ctlcolor1 = gui.addColor(options, 'colormin');
            var ctlmax = gui.add(options, 'max').min(options.min).max(options.max);
            ctlmax.setValue(1500)
            var ctlcolor2 = gui.addColor(options, 'colormax');

            function refresh() {
                map.setPaintProperty('states-layer', 'fill-color', [
                    'interpolate',
                    ['linear'],
                    ['/',['get', 'f176'], ['get', 'area']],
                    options.min,
                    `rgba(${options.colormin.join(',')})`,
                    options.max,
                    `rgba(${options.colormax.join(',')})`,
                ])
            }

            ctlmin.onChange(function (value) {
                refresh();
            });
            ctlmax.onChange(function (value) {
                refresh();
            });
            ctlcolor1.onChange(function (value) {
                refresh();
            });
            ctlcolor2.onChange(function (value) {
                refresh();
            });
        }
    </script>

</body>

</html>